package com.zy.community.web.controller.common;

import com.wf.captcha.SpecCaptcha;
import com.zy.community.common.constant.Constants;
import com.zy.community.common.core.domain.support.Kv;
import com.zy.community.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * 验证码操作处理
 *
 * @author yangdi
 */
@RestController
public class CaptchaController {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Kv getCode(HttpServletResponse response) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);

        // 生成key 和 value
        String uuid = IdUtils.simpleUUID();
        String key = Constants.CAPTCHA_CODE_KEY + uuid;
        String code = specCaptcha.text().toLowerCase();

        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(30));

        return Kv.create().set("uuid",uuid).set("img",specCaptcha.toBase64());
    }
}
